package com.trinity.web.controller.payment.unique;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.trinity.campus.domain.CampusStudents;
import com.trinity.campus.dto.ReleaseStudentOrder;
import com.trinity.campus.service.ICampusStudentsService;
import com.trinity.common.annotation.Log;
import com.trinity.common.core.controller.BaseController;
import com.trinity.common.core.domain.AjaxResult;
import com.trinity.common.core.page.TableDataInfo;
import com.trinity.common.enums.BusinessType;
import com.trinity.common.exception.ServiceException;
import com.trinity.common.utils.StringUtils;
import com.trinity.common.utils.bean.BeanUtils;
import com.trinity.common.utils.poi.ExcelUtil;
import com.trinity.orders.constant.OrderConstants;
import com.trinity.orders.dto.AddOrderDto;
import com.trinity.orders.service.IXcOrdersService;
import com.trinity.uniquefees.domain.UfBookList;
import com.trinity.uniquefees.domain.bo.UfCourseBook;
import com.trinity.uniquefees.domain.bo.UfStudentBook;
import com.trinity.uniquefees.domain.vo.UfStudentBookVO;
import com.trinity.uniquefees.dto.DeptSemesterStuCourseDto;
import com.trinity.uniquefees.dto.RequestReleaseDto;
import com.trinity.uniquefees.dto.UfStudentBookDto;
import com.trinity.uniquefees.service.IUfBookListService;
import com.trinity.uniquefees.service.IUfCourseBookService;
import com.trinity.uniquefees.service.IUfStudentBookService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订购教程名单Controller
 *
 * @author 董诗攀
 * @date 2023-12-11
 */
@RestController
@RequestMapping("/uniquefees/stu_book")
public class UfStudentBookController extends BaseController {
    @Resource
    private IUfStudentBookService ufStudentBookService;

    @Resource
    private IUfBookListService bookListService;

    @Resource
    private IXcOrdersService ordersService;

    @Resource
    private ICampusStudentsService studentsService;

    @Resource
    private IUfCourseBookService ufCourseBookService;

    /**
     * 获取订购教程名单详细信息
     */
    @PreAuthorize("@ss.hasPermi('uniquefees:stu_book:query')")
    @RequestMapping(value = "/items", method = {RequestMethod.GET})
    public AjaxResult getStuBook(UfCourseBook book) {
        return success(ufStudentBookService.selectUfDeptSemesterStuCourse(book));
    }

    /**
     * 查询订购教程名单列表
     */
    @PreAuthorize("@ss.hasPermi('uniquefees:stu_book:list')")
    @GetMapping("/list")
    public TableDataInfo list(UfStudentBook ufStudentBook) {
        startPage();
        List<UfStudentBook> list = ufStudentBookService.selectUfStudentBookList(ufStudentBook);
        return getDataTable(list);
    }

    /**
     * 导出订购教程名单列表
     */
    @PreAuthorize("@ss.hasPermi('uniquefees:stu_book:export')")
    @Log(title = "订购教程名单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UfStudentBook ufStudentBook) {
        List<UfStudentBook> list = ufStudentBookService.selectUfStudentBookList(ufStudentBook);
        ExcelUtil<UfStudentBook> util = new ExcelUtil<UfStudentBook>(UfStudentBook.class);
        util.exportExcel(response, list, "订购教程名单数据");
    }

    /**
     * 获取订购教程名单详细信息
     */
    @PreAuthorize("@ss.hasPermi('uniquefees:stu_book:query')")
    @GetMapping(value = "/{csId}")
    public AjaxResult getInfo(@PathVariable("csId") String csId) {
        return success(ufStudentBookService.selectUfStudentBookByCsId(csId));
    }

    /**
     * 新增订购教程名单
     */
    @PreAuthorize("@ss.hasPermi('uniquefees:stu_book:add')")
    @Log(title = "订购教程名单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody UfStudentBook ufStudentBook) {
        return toAjax(ufStudentBookService.insertUfStudentBook(ufStudentBook));
    }

    /**
     * 修改订购教程名单
     */
    @PreAuthorize("@ss.hasPermi('uniquefees:stu_book:edit')")
    @Log(title = "订购教程名单", businessType = BusinessType.UPDATE)
    @PostMapping("/put")
    public AjaxResult edit(@RequestBody UfStudentBook ufStudentBook) {
        String scheduleId = ufStudentBook.getScheduleId();
        if (StringUtils.isBlank(scheduleId)) {
            throw new ServiceException("数目清单不存在");
        }
        // 添加或更新数据
        Wrapper<UfStudentBook> queryWrapper = new QueryWrapper<>(ufStudentBook); // 使用不同的变量名
        UfStudentBook studentBook = ufStudentBookService.getBaseMapper().selectOne(queryWrapper);
        if (studentBook == null) {
            //新增
            return this.add(ufStudentBook);
        }
        return success();
    }

    /**
     * 删除订购教程名单
     */
    @PreAuthorize("@ss.hasPermi('uniquefees:stu_book:remove')")
    @Log(title = "订购教程名单", businessType = BusinessType.DELETE)
    @PostMapping("/{csIds}/delete")
    public AjaxResult remove(@PathVariable String csIds) {
        return toAjax(ufStudentBookService.deleteUfStudentBookByCsId(csIds));
    }


    /**
     * 发布订购名单  ----缴费账单
     */
    @Log(title = "发布订购名单", businessType = BusinessType.INSERT)
    @PreAuthorize("@ss.hasPermi('uniquefees:stu_book:release')")
    @RequestMapping(value = "/release", method = {RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public AjaxResult release3(@RequestBody RequestReleaseDto dto) {
        //前端传递 缴费项目，服务器自行查询缴费 名单 内容 金额 进行下单
        String scheduleId = dto.getScheduleId();
        //判断状态 进行缴费中的项目 不能再次发布
        UfBookList ufBookList = bookListService.selectUfBookListById(scheduleId);
        if ("2".equals(ufBookList.getStatus())) {
            return error(" 进行缴费中的项目,不能再次发布,请先撤回发布！");
        }
        DeptSemesterStuCourseDto deptSemesterStuCourseDto = ufStudentBookService.selectListStuCourse(scheduleId);
        List<UfStudentBookDto> stuBooks = deptSemesterStuCourseDto.getCourseStu();
        //1.生成账单
        String result = "";
        List<AddOrderDto> addOrderDtoList = new ArrayList<>();
        if (stuBooks != null && !stuBooks.isEmpty()) {
            for (UfStudentBookDto stuBook : stuBooks) {
                AddOrderDto orderDto = new AddOrderDto();
                orderDto.setOrderName(dto.getOrderName());
                //个性化缴费
                orderDto.setOrderType(OrderConstants.PaymentType.UNIQUE);
                //客户 -- 学生
                Long studentId = stuBook.getStudentId();
                orderDto.setCustom(String.valueOf(studentId));
                orderDto.setDeptId(deptSemesterStuCourseDto.getDeptId());
                //数目清单 id + 学生id  每个学生只能缴费一次
                orderDto.setBookListId(scheduleId);
                orderDto.setOutBusinessId(scheduleId + "-" + studentId);
                //价格 -- 单位分
                String totalPrice = stuBook.getTotalPrice();
                orderDto.setTotalPrice(totalPrice);
                orderDto.setOrderDescription(dto.getOrderName() + " " + stuBook.getStudentName());
                //构建商品详情
                String orderDetail = UfStudentBookDto.getStringCourse(stuBook.getCourses());
                orderDto.setOrderDetail(orderDetail);
                //需要缴费的进行下单
                if (Double.parseDouble(totalPrice) > 0) {
                    addOrderDtoList.add(orderDto);
                }
            }
            result = ordersService.release(addOrderDtoList);
        }
        //2.开启缴费状态
        ufBookList.setId(scheduleId);
        //进行中
        ufBookList.setStatus("2");
        bookListService.updateUfBookList(ufBookList);
        return success(result);
    }

    /**
     * 发布订购名单  ----缴费账单 ---单个学生
     */
    @Log(title = "发布订购名单", businessType = BusinessType.INSERT)
    @PreAuthorize("@ss.hasPermi('uniquefees:stu_book:release')")
    @RequestMapping(value = "/release/v4", method = {RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public AjaxResult releaseV4(@RequestBody ReleaseStudentOrder listQuery) {
        String listId = listQuery.getListId();
        UfBookList ufBookList = bookListService.selectUfBookListById(listId);
        //判断状态 未进行缴费中的项目,不能单独发布,请使用批量发布
        if (!"2".equals(ufBookList.getStatus())) {
            return error(" 未进行缴费中的项目,不能单独发布,请使用批量发布！");
        }
        //1.生成账单
        String result = "";
        List<AddOrderDto> addOrderDtoList = new ArrayList<>();
        if (ufBookList != null && ufBookList.getDeptId() != null) {
            Map<Long, CampusStudents> studentsMap = queryStudentMap(ufBookList.getDeptId());
            CampusStudents stu = studentsMap.get(listQuery.getStudentId());
            if (stu!=null){
                AddOrderDto orderDto = new AddOrderDto();
                orderDto.setOrderName(ufBookList.getName());
                orderDto.setDeptId(String.valueOf(ufBookList.getDeptId()));
                //专项
                orderDto.setOrderType(OrderConstants.PaymentType.SPECIAL);
                //客户 -- 学生
                Long studentId = stu.getStudentId();
                orderDto.setCustom(String.valueOf(studentId));
                //数目清单 id + 学生id  每个学生只能缴费一次
                orderDto.setBookListId(listId);
                orderDto.setOutBusinessId(listId + "-" + studentId);
                //价格 -- 单位分
                String totalPrice = String.valueOf(ufBookList.getPricesum());
                orderDto.setTotalPrice(totalPrice);
                orderDto.setOrderDescription(ufBookList.getName() + " " + stu.getStudentName());
                //商品详情  图片
                orderDto.setOrderDetail(ufBookList.getBooklistPic());
                //需要缴费的进行下单
                addOrderDtoList.add(orderDto);
            }
            result = ordersService.release(addOrderDtoList);

        }
        return success(result);
    }

    private Map<Long, CampusStudents> queryStudentMap(Long id){
        List<CampusStudents> list = studentsService.selectCampusStudentsListByDeptId(id);
        // 构建以 studentId 为键的订单映射，提升查找性能
        Map<Long, CampusStudents> studentsMap = new HashMap<>();
        if (list != null) {
            for (CampusStudents stu : list) {
                if (stu.getStudentId() != null) {
                    try {
                        Long studentId = Long.valueOf(stu.getStudentId());
                        CampusStudents student = new CampusStudents();
                        BeanUtils.copyProperties(stu,student);
                        studentsMap.put(studentId, student);
                    } catch (NumberFormatException e) {
                        throw new ServiceException("未找到对应的订单");
                    }
                }
            }
        }
        return studentsMap;
    }

    /**
     * 发布订购名单  -- 专项缴费  ---缴费账单
     */
    @Log(title = "发布订购名单", businessType = BusinessType.INSERT)
    @PreAuthorize("@ss.hasPermi('uniquefees:stu_book:release')")
    @RequestMapping(value = "/release3", method = {RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public AjaxResult releaseList(@RequestBody UfBookList listQuery) {
        String listId = listQuery.getId();
        UfBookList ufBookList = bookListService.selectUfBookListById(listId);
        //判断状态 进行缴费中的项目 不能再次发布
        if ("2".equals(ufBookList.getStatus())) {
            return error(" 进行缴费中的项目,不能再次发布,请先撤回发布！");
        }
        //1.生成账单
        String result = "";
        List<AddOrderDto> addOrderDtoList = new ArrayList<>();
        if (ufBookList != null && ufBookList.getDeptId() != null) {
            List<CampusStudents> list = studentsService.selectCampusStudentsListByDeptId(ufBookList.getDeptId());
            for (CampusStudents stu : list) {
                AddOrderDto orderDto = new AddOrderDto();
                orderDto.setOrderName(ufBookList.getName());
                orderDto.setDeptId(String.valueOf(ufBookList.getDeptId()));
                //专项
                orderDto.setOrderType(OrderConstants.PaymentType.SPECIAL);
                //客户 -- 学生
                Long studentId = stu.getStudentId();
                orderDto.setCustom(String.valueOf(studentId));
                //数目清单 id + 学生id  每个学生只能缴费一次
                orderDto.setBookListId(listId);
                orderDto.setOutBusinessId(listId + "-" + studentId);
                //价格 -- 单位分
                String totalPrice = String.valueOf(ufBookList.getPricesum());
                orderDto.setTotalPrice(totalPrice);
                orderDto.setOrderDescription(ufBookList.getName() + " " + stu.getStudentName());
                //商品详情  图片
                orderDto.setOrderDetail(ufBookList.getBooklistPic());
                //需要缴费的进行下单
                addOrderDtoList.add(orderDto);
            }
            result = ordersService.release(addOrderDtoList);


        }
        //2.开启缴费状态 -- 进行中
        ufBookList.setStatus("2");
        bookListService.updateUfBookList(ufBookList);
        return success(result);
    }


    /**
     * 撤回 发布订购名单 --- 缴费账单
     */
    @Log(title = "撤回发布订购名单", businessType = BusinessType.INSERT)
    @PreAuthorize("@ss.hasPermi('uniquefees:stu_book:release')")
    @RequestMapping(value = "/revoke/release", method = {RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public AjaxResult revokeRelease(@RequestBody RequestReleaseDto dto) {
        //判断是否已经有人进行缴费
        String scheduleId = dto.getScheduleId();
        //判断状态 进行缴费中的项目 不能再次发布
        if (ordersService.hasStudentPaid(scheduleId)) {
            //已经有人进行缴费，不可撤回
            return error("已经有人进行了缴费，不可撤回");
        }
        String result = ordersService.revokeRelease(scheduleId);
        return success(result);
    }

    /**
     * 撤回 发布订单--- 缴费账单
     */
    @Log(title = "撤回发布订单", businessType = BusinessType.INSERT)
    @PreAuthorize("@ss.hasPermi('uniquefees:stu_book:release')")
    @RequestMapping(value = "/revoke/release/v2", method = {RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public AjaxResult revokeReleaseV2(@RequestBody RequestReleaseDto dto) {
        String scheduleId = dto.getScheduleId();
        return success(ordersService.revokeReleaseOne(scheduleId, dto.getStudentId()));
    }

    /**
     * 获取导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<UfStudentBookVO> util = new ExcelUtil<>(UfStudentBookVO.class);
        util.importTemplateExcel(response, "学生选购数据");
    }

    /**
     * 导入
     *
     * @param file
     * @param listId 缴费项目
     * @return
     * @throws Exception
     */
    @Log(title = "账单导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('uniquefees:stu_book:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, String listId) throws Exception {
        ExcelUtil<UfStudentBookVO> util = new ExcelUtil<>(UfStudentBookVO.class);
        List<UfStudentBookVO> list = util.importExcel(file.getInputStream());
        String operName = getUsername();
        //获取学生
        UfBookList ufBookList = bookListService.selectUfBookListById(listId);
        List<UfCourseBook> ufCourseBooks = ufCourseBookService.selectUfCourseBookByListId(listId);
        if (ufBookList != null && ufBookList.getDeptId() != null) {
            List<CampusStudents> student = studentsService.selectCampusStudentsListByDeptId(ufBookList.getDeptId());
            String message = ufStudentBookService.importBill(list, listId, operName, student, ufCourseBooks);
            return success(message);
        }
        return error("数据有误!");
    }

}
